from alipay import AliPay
from alipay.utils import AliPayConfig
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import render
from django.views import View
from meiduo_mall import settings
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin
from .models import Payment
from apps.orders.models import OrderInfo

# Create your views here.


class PaymentView(LoginRequiredJSONMixin, View):
    """订单支付"""

    def get(self, request, order_id):
        """订单支付"""
        try:
            # 获取订单信息，必须是未支付的订单
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=request.user,
                                          status=1)
        except OrderInfo.DoesNotExist:
            return HttpResponseBadRequest('订单错误')

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )

        subject = "测试订单"  # 提示信息

        # 电脑网站支付，需要跳转到：https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 拼接跳转的url
        pay_url = settings.ALIPAY_URL + '?' + order_string

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK',
                             'pay_url': pay_url})


class PayStatusView(View):
    """支付状态展示"""

    def get(self, request):
        """保存订单号和支付宝流水号"""
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        # for django users
        data = request.dict()

        signature = data.pop("sign")

        # verification
        success = alipay.verify(data, signature)
        if success:
            trade_no = data.get('trade_no')  # 支付宝交易号
            out_trade_no = data.get('out_trade_no')  # 订单号

            Payment.objects.create(
                order=out_trade_no,
                trade_id=trade_no
            )

        return render(request, 'pay_success.html',
                      context={'trade_no': trade_no})
